"""
用户模块API视图
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.db.models import Q

from .models import UserProfile
from .serializers import (
    UserSerializer, UserDetailSerializer, 
    LoginSerializer, UserProfileSerializer
)


@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
    """
    用户登录接口
    
    请求参数:
        - username: 用户名
        - password: 密码
    
    返回:
        - token: 认证令牌
        - user: 用户信息
    """
    serializer = LoginSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    
    username = serializer.validated_data['username']
    password = serializer.validated_data['password']
    
    # 验证用户
    user = authenticate(username=username, password=password)
    
    if user is None:
        return Response({
            'code': 401,
            'message': '用户名或密码错误'
        }, status=status.HTTP_401_UNAUTHORIZED)
    
    if not user.is_active:
        return Response({
            'code': 403,
            'message': '该账号已被禁用'
        }, status=status.HTTP_403_FORBIDDEN)
    
    # 获取或创建Token
    token, created = Token.objects.get_or_create(user=user)
    
    # 返回用户信息
    user_serializer = UserDetailSerializer(user)
    
    return Response({
        'code': 200,
        'message': '登录成功',
        'data': {
            'token': token.key,
            'user': user_serializer.data
        }
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def logout(request):
    """
    用户登出接口
    
    删除当前用户的Token
    """
    try:
        # 删除Token
        request.user.auth_token.delete()
        return Response({
            'code': 200,
            'message': '登出成功'
        })
    except Exception as e:
        return Response({
            'code': 500,
            'message': f'登出失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def current_user(request):
    """
    获取当前登录用户信息
    
    返回当前用户的详细信息
    """
    serializer = UserDetailSerializer(request.user)
    return Response(serializer.data)


class UserViewSet(viewsets.ModelViewSet):
    """
    用户管理ViewSet
    
    提供用户的CRUD操作:
        - list: 获取用户列表（支持搜索、筛选、分页）
        - retrieve: 获取用户详情
        - create: 创建用户
        - update: 更新用户信息
        - destroy: 删除用户
        - submit_cet: 提交四六级成绩
        - review_cet: 审核四六级成绩
    """
    queryset = User.objects.all().select_related('profile')
    serializer_class = UserSerializer
    
    def get_serializer_class(self):
        """根据不同的action返回不同的序列化器"""
        if self.action == 'retrieve':
            return UserDetailSerializer
        return UserSerializer
    
    def get_queryset(self):
        """
        根据用户权限返回不同的查询集
        
        - 超级管理员: 可以查看所有用户
        - 普通用户: 只能查看自己和下级
        """
        user = self.request.user
        queryset = User.objects.all().select_related('profile')
        
        # 超级管理员可以看到所有用户
        if user.is_superuser:
            pass
        elif hasattr(user, 'profile'):
            # 获取自己和所有下级
            subordinate_users = user.profile.get_all_subordinates()
            subordinate_ids = [u.id for u in subordinate_users]
            subordinate_ids.append(user.id)
            queryset = queryset.filter(id__in=subordinate_ids)
        else:
            # 只能看到自己
            queryset = queryset.filter(id=user.id)
        
        # 搜索功能
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(username__icontains=search) |
                Q(email__icontains=search) |
                Q(first_name__icontains=search) |
                Q(last_name__icontains=search) |
                Q(profile__student_id__icontains=search) |
                Q(profile__employee_id__icontains=search)
            )
        
        # 班级筛选
        class_name = self.request.query_params.get('class_name', None)
        if class_name:
            queryset = queryset.filter(profile__class_name=class_name)
        
        # 专业筛选
        major = self.request.query_params.get('major', None)
        if major:
            queryset = queryset.filter(profile__major=major)
        
        return queryset
    
    def create(self, request, *args, **kwargs):
        """
        创建用户
        
        需要管理员权限
        """
        if not request.user.is_staff:
            return Response({
                'code': 403,
                'message': '权限不足，仅管理员可创建用户'
            }, status=status.HTTP_403_FORBIDDEN)
        
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        
        return Response({
            'code': 201,
            'message': '创建成功',
            'data': serializer.data
        }, status=status.HTTP_201_CREATED)
    
    def update(self, request, *args, **kwargs):
        """更新用户信息"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        
        return Response({
            'code': 200,
            'message': '更新成功',
            'data': serializer.data
        })
    
    def destroy(self, request, *args, **kwargs):
        """
        删除用户
        
        需要管理员权限
        """
        if not request.user.is_staff:
            return Response({
                'code': 403,
                'message': '权限不足，仅管理员可删除用户'
            }, status=status.HTTP_403_FORBIDDEN)
        
        instance = self.get_object()
        self.perform_destroy(instance)
        
        return Response({
            'code': 204,
            'message': '删除成功'
        }, status=status.HTTP_204_NO_CONTENT)
    
    @action(detail=False, methods=['post'])
    def submit_cet(self, request):
        """
        提交四六级成绩
        
        接口：POST /api/users/submit_cet/
        权限：已认证用户
        
        参数:
            - exam_type: 考试类型（cet4/cet6）
            - score: 成绩
            - exemption_pic: 免修证明图片URL（带姓名）
            - score_pic: 成绩证明图片URL（带姓名和分数）
        
        返回:
            - code: 状态码
            - message: 提示信息
            - data: 更新后的用户信息
        """
        exam_type = request.data.get('exam_type')
        score = request.data.get('score')
        exemption_pic = request.data.get('exemption_pic')
        score_pic = request.data.get('score_pic')
        
        if not exam_type or exam_type not in ['cet4', 'cet6']:
            return Response({
                'code': 400,
                'message': '请指定正确的考试类型（cet4/cet6）'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        if not score:
            return Response({
                'code': 400,
                'message': '请输入成绩'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        if not exemption_pic:
            return Response({
                'code': 400,
                'message': '请上传免修证明图片（带姓名）'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        if not score_pic:
            return Response({
                'code': 400,
                'message': '请上传成绩证明图片（带姓名和分数）'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            score = int(score)
            if score < 0 or score > 710:
                return Response({
                    'code': 400,
                    'message': '成绩范围应为0-710分'
                }, status=status.HTTP_400_BAD_REQUEST)
        except ValueError:
            return Response({
                'code': 400,
                'message': '成绩必须为整数'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        user = request.user
        
        # 确保用户有profile，如果没有则创建
        if not hasattr(user, 'profile') or user.profile is None:
            from .models import UserProfile
            UserProfile.objects.create(user=user)
            user.refresh_from_db()
        
        profile = user.profile
        
        # 更新成绩、状态和图片
        if exam_type == 'cet4':
            # 检查是否已通过审核
            if profile.cet4_status == '已通过':
                return Response({
                    'code': 400,
                    'message': '四级成绩已通过审核，无法修改'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            profile.cet4_score = score
            profile.cet4_status = '审核中'
            profile.cet4_exemption_pic = exemption_pic
            profile.cet4_score_pic = score_pic
            exam_name = '英语四级'
        else:
            # 检查是否已通过审核
            if profile.cet6_status == '已通过':
                return Response({
                    'code': 400,
                    'message': '六级成绩已通过审核，无法修改'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            profile.cet6_score = score
            profile.cet6_status = '审核中'
            profile.cet6_exemption_pic = exemption_pic
            profile.cet6_score_pic = score_pic
            exam_name = '英语六级'
        
        profile.save()
        
        serializer = UserDetailSerializer(user)
        return Response({
            'code': 200,
            'message': f'{exam_name}成绩提交成功，等待审核',
            'data': serializer.data
        })
    
    @action(detail=True, methods=['post'])
    def review_cet(self, request, pk=None):
        """
        审核四六级成绩
        
        接口：POST /api/users/{id}/review_cet/
        权限：仅管理员
        
        参数:
            - exam_type: 考试类型（cet4/cet6）
            - action: 审核操作（approve/reject）
            - reason: 拒绝原因（拒绝时必填）
        
        返回:
            - code: 状态码
            - message: 提示信息
            - data: 更新后的用户信息
        """
        if not request.user.is_staff:
            return Response({
                'code': 403,
                'message': '权限不足，仅管理员可审核'
            }, status=status.HTTP_403_FORBIDDEN)
        
        exam_type = request.data.get('exam_type')
        action = request.data.get('action')
        reason = request.data.get('reason', '')
        
        if not exam_type or exam_type not in ['cet4', 'cet6']:
            return Response({
                'code': 400,
                'message': '请指定正确的考试类型（cet4/cet6）'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        if not action or action not in ['approve', 'reject']:
            return Response({
                'code': 400,
                'message': '请指定正确的审核操作（approve/reject）'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        if action == 'reject' and not reason:
            return Response({
                'code': 400,
                'message': '拒绝时必须填写原因'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        user = self.get_object()
        
        # 确保用户有profile
        if not hasattr(user, 'profile') or user.profile is None:
            return Response({
                'code': 400,
                'message': '该用户没有个人资料，无法审核'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        profile = user.profile
        
        if exam_type == 'cet4':
            current_status = profile.cet4_status
            exam_name = '英语四级'
            
            # 防止重复审核
            if current_status == '已通过':
                return Response({
                    'code': 400,
                    'message': '该成绩已通过审核，无法重复审核'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if current_status != '审核中':
                return Response({
                    'code': 400,
                    'message': '该成绩未处于审核中状态'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if action == 'approve':
                profile.cet4_status = '已通过'
                profile.cet4_reject_reason = ''  # 清空拒绝理由
                message = f'{exam_name}成绩审核通过'
            else:
                profile.cet4_status = '未通过'
                profile.cet4_reject_reason = reason  # 保存拒绝理由
                message = f'{exam_name}成绩审核未通过：{reason}'
        else:
            current_status = profile.cet6_status
            exam_name = '英语六级'
            
            # 防止重复审核
            if current_status == '已通过':
                return Response({
                    'code': 400,
                    'message': '该成绩已通过审核，无法重复审核'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if current_status != '审核中':
                return Response({
                    'code': 400,
                    'message': '该成绩未处于审核中状态'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if action == 'approve':
                profile.cet6_status = '已通过'
                profile.cet6_reject_reason = ''  # 清空拒绝理由
                message = f'{exam_name}成绩审核通过'
            else:
                profile.cet6_status = '未通过'
                profile.cet6_reject_reason = reason  # 保存拒绝理由
                message = f'{exam_name}成绩审核未通过：{reason}'
        
        profile.save()
        
        serializer = UserDetailSerializer(user)
        return Response({
            'code': 200,
            'message': message,
            'data': serializer.data
        })
